package frontend;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;

public class ErrorList {
    private static ErrorList errorList;
    private ArrayList<ErrorInf> errorInfs = new ArrayList<>();
    public static ErrorList getInstance() {
        if (errorList == null) {
            errorList = new ErrorList();
        }
        return errorList;
    }

    public void insertError(ErrorInf errorInf) {
        errorInfs.add(errorInf);
    }

    public int getErrorSize() {
        return errorInfs.size();
    }

    public void insertError(int line, String type) {
        ErrorInf errorInf = new ErrorInf(line,type);
        errorInfs.add(errorInf);
    }

    public void resetError(int size) {
        if (size < errorInfs.size()) {
            errorInfs.subList(size, errorInfs.size()).clear();
        }
    }

    public void sysError(String s, int line) {
        System.out.println(s + " at " + line);
        System.exit(1);
    }
    public void outputAll() {
        int len = errorInfs.size();
        errorInfs.sort(ErrorInf::compareTo);
        try (FileWriter writer = new FileWriter("error.txt")) {
            // 向文件中写入内容
            for (int i = 0;i < len;i++) {
                System.out.println(errorInfs.get(i).toString());
                writer.write(errorInfs.get(i).toString() + '\n');
            }
        } catch (IOException e) {
            // 捕获并处理可能发生的IO异常
            System.out.println("An error occurred while writing to the file.");
            e.printStackTrace();
        }
    }
}
